package com.hjt.tools.model;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtilsBean;

/**
 * 属性工具类
 * @author wuzc
 */
public class PropertyUtil {

	/**
	 * 保留目标对象基础属性，克隆源对象非空属性
	 * @param dest 目标对象
	 * @param orig 源对象
	 */
	@SuppressWarnings("all")
	public void copyNotNullProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
		if (dest == null)
			throw new IllegalArgumentException("No destination bean specified");
		if (orig == null)
			throw new IllegalArgumentException("No origin bean specified");
		if (orig instanceof DynaBean) {
			DynaProperty origDescriptors[] = ((DynaBean) orig).getDynaClass().getDynaProperties();
			for (int i = 0; i < origDescriptors.length; i++) {
				String name = origDescriptors[i].getName();
				if (dest instanceof DynaBean) {
					if (propertyUtilsBean.isWriteable(dest, name)) {
						Object value = ((DynaBean) orig).get(name);
						if (value != null) {
							((DynaBean) dest).set(name, value);
						}
					}
				} else if (propertyUtilsBean.isWriteable(dest, name)) {
					Object value = ((DynaBean) orig).get(name);
					if(value != null){
						propertyUtilsBean.setSimpleProperty(dest, name, value);
					}
				}
			}

		} else if (orig instanceof Map) {
			for (Iterator names = ((Map) orig).keySet().iterator(); names.hasNext();) {
				String name = (String) names.next();
				if (dest instanceof DynaBean) {
					if (propertyUtilsBean.isWriteable(dest, name)) {
						Object value = ((Map) orig).get(name);
						if(value != null){
							((DynaBean) dest).set(name, value);
						}
					}
				} else if (propertyUtilsBean.isWriteable(dest, name)) {
					Object value = ((Map) orig).get(name);
					if(value != null){
						propertyUtilsBean.setSimpleProperty(dest, name, value);
					}
				}
			}

		} else {
			PropertyDescriptor origDescriptors[] = propertyUtilsBean.getPropertyDescriptors(orig);
			for (int i = 0; i < origDescriptors.length; i++) {
				String name = origDescriptors[i].getName();
				if (propertyUtilsBean.isReadable(orig, name))
					if (dest instanceof DynaBean) {
						if (propertyUtilsBean.isWriteable(dest, name)) {
							Object value = propertyUtilsBean.getSimpleProperty(orig, name);
							if(value != null){
								((DynaBean) dest).set(name, value);
							}
						}
					} else if (propertyUtilsBean.isWriteable(dest, name)) {
						Object value = propertyUtilsBean.getSimpleProperty(orig, name);
						if(value != null){
							propertyUtilsBean.setSimpleProperty(dest, name, value);
						}
					}
			}

		}
	}
}
